package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User register(UserLoginDTO userLoginDTO) {
        try {
            String openId =  getOpenid(userLoginDTO.getCode());
            log.info("openId{}",openId);
            //判断openid是不是为null，为null报出异常
            if (openId == null) {
                throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
            }
            //根据openid查询数据库看有没有数据
            User user = userMapper.selectByOpenId(openId);
            if (user == null){
                user = User.builder().openid(openId).createTime(LocalDateTime.now()).build();
                userMapper.insertUser(user);
            }

            return user;

        } catch (IOException | URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    private String getOpenid(String code) throws IOException, URISyntaxException {
        String url = "https://api.weixin.qq.com/sns/jscode2session";

        //创建map添加appid + appsecret + code
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        CloseableHttpClient client = null;
        try {
            //创建对象
            client = HttpClients.createDefault();

            URIBuilder builder = new URIBuilder(url);
            if(map != null){
                for (String key : map.keySet()) {
                    builder.addParameter(key,map.get(key));
                }
            }
                //创建请求对象
                URI uri = builder.build();
                HttpGet httpGet = new HttpGet(uri);
            //发送请求
            CloseableHttpResponse response = client.execute(httpGet);
            //获取状态码
            int statusCode = response.getStatusLine().getStatusCode();
            log.info("状态码:{}",statusCode);
            String json = null;
            if (statusCode == 200) {
                json = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            //这个存json字符串要转为对象
            JSONObject jsonObject = JSON.parseObject(json);
            return jsonObject.getString("openid");
        } finally {
            client.close();
        }
    }
}
